package com.zhu.transaction.service.imp;

import com.zhu.transaction.mapper.MessageMapper;
import com.zhu.transaction.mapper.UserMapper;
import com.zhu.transaction.pojo.Message;
import com.zhu.transaction.pojo.state.BackState;
import com.zhu.transaction.pojo.state.MessageState;
import com.zhu.transaction.service.MessageService;
import com.zhu.transaction.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhuzhu
 * @createtime 2021/3/4-9:54
 */
@Service
public class MessageServiceImp implements MessageService {
    @Autowired
    MessageMapper messageMapper;

    @Autowired
    UserMapper userMapper;

    /**
     * 新增一条消息信息
     *
     * @param message 消息实体
     * @return 新增结果
     */
    @Override
    public BackState addMessage(Message message) {
        message.setId(MyUtils.getRandomID()).setTime(new Date()).setMessageState(MessageState.MESSAGE_NO_READ);
        return messageMapper.addOneMessage(message) > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 更新消息状态
     *
     * @param messageId 消息Id
     * @return 更新结果
     */
    @Override
    public BackState updateMessage(String messageId) {
        return messageMapper.updateMessageState(messageId, MessageState.MESSAGE_HAS_READ) > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 获取消息列表
     *
     * @param userId 接受用户的Id
     * @return 消息列表
     */
    @Override
    public List<Message> getMessageByReceiveUser(String userId) {
        List<Message> messageList = messageMapper.queryMessageByReceiveUserId(userId);
        for (Message message : messageList) {
            message.setSendUserPojo(userMapper.queryUserByID(message.getSendUser()));
        }
        return messageList;
    }

    /**
     * 获取消息未读数量
     *
     * @param userId 用户Id
     * @return 消息未读数
     */
    @Override
    public Integer getUnReadMessageCount(String userId) {
        return messageMapper.unReadMessageCount(userId);
    }

    /**
     * 删除消息
     *
     * @param messageId 消息ID
     * @return 删除结果
     */
    @Override
    public BackState deleteOneMessage(String messageId) {
        return messageMapper.deleteOneMessage(messageId) > 0 ? BackState.SUCCESS : BackState.ERROR;
    }
}
